package cn.com.thingo.shyintelligent.ui.fragment;


import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.th.opensdk.openapi.CurtainInfo;
import com.th.opensdk.openapi.DimmerInfo;
import com.th.opensdk.openapi.RemoterInfo;
import com.th.opensdk.openapi.RoomInfo;
import com.th.opensdk.openapi.SceneGroupInfo;
import com.th.opensdk.openapi.SceneInfo;
import com.th.opensdk.openapi.SwitchInfo;
import com.th.opensdk.openapi.THOpenSDK;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.shyintelligent.R;
import cn.com.thingo.shyintelligent.app.App;
import cn.com.thingo.shyintelligent.base.RootFragment;
import cn.com.thingo.shyintelligent.base.contract.ControlContract;
import cn.com.thingo.shyintelligent.model.bean.CommonBean;
import cn.com.thingo.shyintelligent.model.bean.DeviceBean;
import cn.com.thingo.shyintelligent.presenter.ControlPresenter;
import cn.com.thingo.shyintelligent.ui.activity.AirConditionActivity;
import cn.com.thingo.shyintelligent.ui.activity.AreaSelectActivity;
import cn.com.thingo.shyintelligent.ui.activity.CurtainActivity;
import cn.com.thingo.shyintelligent.ui.activity.DoorLockActivity;
import cn.com.thingo.shyintelligent.ui.activity.LiteActivity;
import cn.com.thingo.shyintelligent.ui.activity.MessageActivity;
import cn.com.thingo.shyintelligent.ui.activity.MusicActivity;
import cn.com.thingo.shyintelligent.ui.activity.PersonalActivity;
import cn.com.thingo.shyintelligent.ui.activity.WindowActivity;
import cn.com.thingo.shyintelligent.ui.adapter.CommonScenesAdapter;
import cn.com.thingo.shyintelligent.ui.adapter.DeviceAdapter;
import cn.com.thingo.shyintelligent.util.SPUtils;
import cn.com.thingo.shyintelligent.util.ToastUtil;

public class ControlFragment extends RootFragment<ControlPresenter> implements ControlContract.View, DeviceAdapter.OnItemClickListener, CommonScenesAdapter.OnItemClickListener {
    @BindView(R.id.control_personal)
    ImageView ivPersonal;
    @BindView(R.id.control_message)
    ImageView ivMessage;
    @BindView(R.id.control_room)
    TextView tvRoom;
    @BindView(R.id.control_weather)
    TextView tvWeather;
    @BindView(R.id.control_scenes)
    View vScenes;
    @BindView(R.id.control_commonly_used_scenes_list)
    RecyclerView rvScenes;
    @BindView(R.id.control_device_manager_list)
    RecyclerView rvDevice;
    private THOpenSDK thOpenSDK;
    private int currentRoomId = -1;
    private List<DeviceBean> deviceList = new ArrayList<>();
    private List<SceneInfo> sceneList = new ArrayList<>();
    private DeviceAdapter adapter;
    private CommonScenesAdapter scenesAdapter;


    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        thOpenSDK = THOpenSDK.getInstance();
        initView();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (deviceList.size() > 0) {
            deviceList.clear();
        }
        if (sceneList.size() > 0) {
            sceneList.clear();
        }
        initData();
        adapter.notifyDataSetChanged();
        scenesAdapter.notifyDataSetChanged();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (deviceList.size() > 0) {
                deviceList.clear();
            }
            if (sceneList.size() > 0) {
                sceneList.clear();
            }
            initData();
            adapter.notifyDataSetChanged();
            scenesAdapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        adapter = new DeviceAdapter(deviceList, mContext);
        rvDevice.setLayoutManager(new GridLayoutManager(mContext, 4));
        adapter.setListener(this);
        rvDevice.setAdapter(adapter);
        rvScenes.setLayoutManager(new GridLayoutManager(mContext, 4));
        scenesAdapter = new CommonScenesAdapter(sceneList, mContext);
        scenesAdapter.setListener(this);
        rvScenes.setAdapter(scenesAdapter);
    }

    private void initData() {
        if (thOpenSDK == null) {
            thOpenSDK = THOpenSDK.getInstance();
        }
        initRoom();
        initDevice();
        initCommonScenes();
    }

    private void initCommonScenes() {
        List<SceneGroupInfo> sceneGroupList = thOpenSDK.getSceneGroupList();
        List<SceneInfo> sceneInfoList = new ArrayList<>();
        List<SceneInfo> sceneList = new ArrayList<>();
        if (sceneGroupList != null && sceneGroupList.size() > 0) {
            for (int i = 0; i < sceneGroupList.size(); i++) {
                sceneInfoList.addAll(sceneGroupList.get(i).getSceneList());
            }
            if (sceneInfoList.size() > 0) {
                for (int i = 0; i < sceneInfoList.size(); i++) {
                    if (!sceneInfoList.get(i).getSceneName().startsWith("窗户-")) {
                        sceneList.add(sceneInfoList.get(i));
                    }
                }
            }
        }
        String selectPositions = SPUtils.newInstance().getString("scenes_num".concat(App.getDataBean().getNumber()));
        if (selectPositions != null) {
            String[] split = selectPositions.split(",");
            for (int i = 0; i < sceneList.size(); i++) {
                for (String aSplit : split) {
                    if (TextUtils.equals(String.valueOf(i), aSplit)) {
                        this.sceneList.add(sceneList.get(i));
                        break;
                    }
                }
            }
        }
        if (this.sceneList.size() > 0) {
            vScenes.setVisibility(View.VISIBLE);
            scenesAdapter.notifyDataSetChanged();
        } else {
            vScenes.setVisibility(View.GONE);
        }
    }

    private void initDevice() {
        initCurtain();
        initGlass();
        initLite();
        initWindow();
        initIcebox();
        initTelevision();
        List<RemoterInfo> remoterList = thOpenSDK.getRemoterList();
        if (remoterList != null && remoterList.size() > 0) {
            initAirCondition(remoterList);
            initDoorLock(remoterList);
            initMusic(remoterList);
        }
    }

    private void initMusic(List<RemoterInfo> remoterList) {
        boolean musicFlag = false;//判断当前房间是否有音乐
        if (remoterList != null && remoterList.size() > 0) {
            for (int i = 0; i < remoterList.size(); i++) {
                int roomId = remoterList.get(i).getRoomId();
                int controlType = remoterList.get(i).getRemoterType();
                if (roomId == currentRoomId && controlType == RemoterInfo.HOME_REMOTER_TYPE_MUSIC) {
                    musicFlag = true;
                    break;
                }
            }
        }
        if (musicFlag) {
            deviceList.add(new DeviceBean("音乐", R.mipmap.music));
            adapter.notifyDataSetChanged();
        }
    }

    private void initDoorLock(List<RemoterInfo> remoterList) {
        boolean doorLockFlag = false;//判断当前房间是否有门锁
        if (remoterList != null && remoterList.size() > 0) {
            for (int i = 0; i < remoterList.size(); i++) {
                int roomId = remoterList.get(i).getRoomId();
                int controlType = remoterList.get(i).getRemoterType();
                if (roomId == currentRoomId && controlType == RemoterInfo.HOME_REMOTER_TYPE_LOCKER) {
                    doorLockFlag = true;
                    break;
                }
            }
        }
        if (doorLockFlag) {
            deviceList.add(new DeviceBean("门锁", R.mipmap.door_lock));
            adapter.notifyDataSetChanged();
        }
    }

    private void initWindow() {
        List<SceneInfo> sceneInfoList = new ArrayList<>();
        List<SceneGroupInfo> sceneGroupList = thOpenSDK.getSceneGroupList();
        for (int i = 0; i < sceneGroupList.size(); i++) {
            List<SceneInfo> sceneList = sceneGroupList.get(i).getSceneList();
            if (sceneList.size() > 0) {
                sceneInfoList.addAll(sceneList);
            }
        }
        boolean windowFlag = false;
        if (sceneInfoList.size() > 0) {
            for (int i = 0; i < sceneInfoList.size(); i++) {
                if (currentRoomId == sceneInfoList.get(i).getRoomId() && sceneInfoList.get(i).getSceneName().startsWith("窗户-")) {
                    windowFlag = true;
                    break;
                }
            }
        }
        if (windowFlag) {
            deviceList.add(new DeviceBean("窗户", R.mipmap.window));
            adapter.notifyDataSetChanged();
        }

    }

    private void initLite() {
        List<DimmerInfo> dimmerList = thOpenSDK.getDimmerList();
        List<SwitchInfo> switchList = thOpenSDK.getSwitchList();
        boolean liteFlag = false;
        if (dimmerList != null && dimmerList.size() > 0) {
            for (int i = 0; i < dimmerList.size(); i++) {
                if (dimmerList.get(i).getRoomId() == currentRoomId) {
                    liteFlag = true;
                    break;
                }
            }
        }
        if (liteFlag) {
            deviceList.add(new DeviceBean("灯光", R.mipmap.lite));
            adapter.notifyDataSetChanged();
        } else {
            if (switchList != null && switchList.size() > 0) {
                for (int i = 0; i < switchList.size(); i++) {
                    if (switchList.get(i).getRoomId() == currentRoomId) {
                        liteFlag = true;
                        break;
                    }
                }
            }
            if (liteFlag) {
                deviceList.add(new DeviceBean("灯光", R.mipmap.lite));
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void initAirCondition(List<RemoterInfo> remoterList) {
        if (remoterList != null && remoterList.size() > 0) {
            boolean airConditionFlag = false;
            for (int i = 0; i < remoterList.size(); i++) {
                if (remoterList.get(i).getRoomId() == currentRoomId && remoterList.get(i).getRemoterType() == RemoterInfo.HOME_REMOTER_TYPE_AIR_CONDITION) {
                    airConditionFlag = true;
                    break;
                }
            }
            if (airConditionFlag) {
                deviceList.add(new DeviceBean("空调", R.mipmap.air_condition));
                adapter.notifyDataSetChanged();
            }
        }
    }

    //todo 电视
    private void initTelevision() {

    }

    //todo 冰箱
    private void initIcebox() {

    }

    //todo 玻璃
    private void initGlass() {

    }

    private void initCurtain() {
        List<CurtainInfo> curtainList = thOpenSDK.getCurtainList();
        if (curtainList != null && curtainList.size() > 0) {
            boolean curtainFlag = false;
            for (int i = 0; i < curtainList.size(); i++) {
                if (currentRoomId == curtainList.get(i).getRoomId()) {
                    curtainFlag = true;
                    break;
                }
            }
            if (curtainFlag) {
                deviceList.add(new DeviceBean("窗帘", R.mipmap.curtain));
                adapter.notifyDataSetChanged();
            }
        }
    }


    private void initRoom() {
        List<RoomInfo> roomList = thOpenSDK.getRoomList();
        if (roomList != null && roomList.size() > 0) {
            if (currentRoomId == -1) {
                currentRoomId = roomList.get(0).getRoomId();
                tvRoom.setText(roomList.get(0).getRoomName());
                SPUtils.newInstance().put(SPUtils.CURRENT_ROOM_ID, currentRoomId);
                App.getInstance().setCurrentRoomInfo(roomList.get(0));
            } else {
                RoomInfo currentRoomInfo = App.getInstance().getCurrentRoomInfo();
                currentRoomId = currentRoomInfo.getRoomId();
                tvRoom.setText(currentRoomInfo.getRoomName());
            }
        }
    }

    @OnClick({R.id.control_personal, R.id.control_message, R.id.control_room})
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.control_room:
                //选择房间
                intent.setClass(mContext, AreaSelectActivity.class);
                startActivity(intent);
                break;
            case R.id.control_message:
                //个人消息
                intent.setClass(mContext, MessageActivity.class);
                startActivity(intent);
                break;
            case R.id.control_personal:
                //个人中心
                intent.setClass(mContext, PersonalActivity.class);
                startActivity(intent);
                break;
        }
    }

    public ControlFragment() {
    }

    public static ControlFragment newInstance() {
        return new ControlFragment();
    }


    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_control;
    }

    @Override
    public void onItemClick(int position) {
        DeviceBean deviceBean = deviceList.get(position);
        Intent intent = new Intent();
        switch (deviceBean.getIcon()) {
            case R.mipmap.lite:
                //灯光
                intent.setClass(mContext, LiteActivity.class);
                intent.putExtra("current_room_id", currentRoomId);
                startActivity(intent);
                break;
            case R.mipmap.music:
                //音乐
                intent.setClass(mContext, MusicActivity.class);
                intent.putExtra("current_room_id", currentRoomId);
                startActivity(intent);
                break;
            case R.mipmap.door_lock:
                //门锁
                intent.setClass(mContext, DoorLockActivity.class);
                intent.putExtra("current_room_id", currentRoomId);
                startActivity(intent);
                break;
            case R.mipmap.window:
                //窗户
                intent.setClass(mContext, WindowActivity.class);
                intent.putExtra("current_room_id", currentRoomId);
                startActivity(intent);
                break;
            case R.mipmap.air_condition:
                //空调
                intent.setClass(mContext, AirConditionActivity.class);
                intent.putExtra("current_room_id", currentRoomId);
                startActivity(intent);
                break;
            case R.mipmap.curtain:
                //窗帘
                intent.setClass(mContext, CurtainActivity.class);
                intent.putExtra("current_room_id", currentRoomId);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onSceneItemClick(int position) {
        final SceneInfo sceneInfo = sceneList.get(position);
        if (App.getInstance().isScenesStatus()) {
            //场景开关控制
            App.getInstance().setScenesStatus(false);
            long controlId = sceneInfo.getControlId();
            App.getInstance().setCurrentScenesId(controlId);
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    sceneInfo.run();
                }
            }.start();
        } else {
            ToastUtil.shortShow("有其他场景的操作正在部署中...");
        }
    }

    @Override
    public void viewMessageCount(CommonBean commonBean) {
        int count = commonBean.getCount();
        if (count == 0) {
            ivMessage.setImageResource(R.mipmap.message);
        } else {
            ivMessage.setImageResource(R.mipmap.message_count);

        }
    }

    public void messageCount() {
        mPresenter.messageCount(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
    }
}
